package utils

import (
	"os"
	"path"
	"time"

	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
)

var Log = logrus.New()

//InitLog 初始化日志配置
func InitLog(dir, filename, level string, timeout int) error {
	Log.Out = os.Stdout
	//判断日志路径是否存在，不存在则创建
	if _, err := os.Stat(dir); os.IsNotExist(err) {
		err = os.MkdirAll(dir, os.ModePerm)
		if err != nil {
			return err
		}
	}
	filePath := path.Join(dir, filename) //构建路径

	//设置日志输出格式
	Log.SetFormatter(&logrus.JSONFormatter{})

	//设置日志等级
	var logLevel logrus.Level
	switch level {
	case "trace":
		logLevel = logrus.TraceLevel
	case "debug":
		logLevel = logrus.DebugLevel
	case "info":
		logLevel = logrus.InfoLevel
	case "warning":
		logLevel = logrus.WarnLevel
	case "error":
		logLevel = logrus.ErrorLevel
	case "fatal":
		logLevel = logrus.FatalLevel
	case "panic":
		logLevel = logrus.PanicLevel
	default:
		logLevel = logrus.InfoLevel
	}
	Log.SetLevel(logLevel)

	//分割
	writer, err := rotatelogs.New(
		filePath+".%Y%m%d.log",                                     //分割后的文件名称
		rotatelogs.WithLinkName(filePath),                          //生成软链，指向最新日志文件
		rotatelogs.WithMaxAge(time.Duration(timeout)*time.Hour*24), //设置最大保存时间
		rotatelogs.WithRotationTime(24*time.Hour),                  //设置日志切割时间间隔
	)
	if err != nil {
		return err
	}
	writeMap := lfshook.WriterMap{
		logrus.InfoLevel:  writer,
		logrus.FatalLevel: writer,
		logrus.DebugLevel: writer,
		logrus.WarnLevel:  writer,
		logrus.ErrorLevel: writer,
		logrus.PanicLevel: writer,
	}
	lfHook := lfshook.NewHook(writeMap, &logrus.JSONFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
	})

	// 新增 Hook
	Log.AddHook(lfHook)

	//写入文件
	file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		return err
	}
	Log.Out = file

	return nil
}
